import media from '@ohos.multimedia.media';
import http from '@ohos.net.http';
import prompt from '@system.prompt';
import featureAbility from '@ohos.ability.featureAbility';
import data_storage from '@ohos.data.storage';
import router from '@system.router';

var detectIntervalID = null;
// setInterval() 方法：在固定的时间间隔内重复调用一个函数或代码片段，在每次调用之间具有固定的时间间隔，
// 它返回一个interval ID，该 ID 唯一地标识时间间隔。变量detectIntervalID表示interval ID
// 检测过程的interval ID
//定义一个全局变量的轻量级数据库对象
let storage;
export default {
    data: {
        counter: 5,  // 倒计时计数
        percentage:'100',  // 百分比
        progress: 10,

        // 1.手指捏合
        vals11:"-",
        vals12:"-",
        vals13:1,
        // 2.手指伸展
        vals21:"-",
        vals22:"-",
        vals23:"-",
        vals24:"-",
        vals25:"-",
        vals26:2,
        // 3.手部震颤
        vals31:"-",
        vals32:"-",
        vals33:0.00025,
        vals34:3,
        //图标数据
        lindData1:[
            0.0,
            0.46875,
            0.9375,
            1.40625,
            1.875,
            2.34375,
            2.8125,
            3.28125,
            3.75,
            4.21875,
            4.6875,
            5.15625,
            5.625,
            6.09375,
            6.5625,
            7.03125,
            7.5,
            7.96875,
            8.4375,
            8.90625,
            9.375,
            9.84375,
            10.3125,
            10.78125,
            11.25,
            11.71875,
            12.1875,
            12.65625,
            13.125,
            13.59375,
            14.0625,
            14.53125,
            15.0,
            15.46875,
            15.9375,
            16.40625,
            16.875,
            17.34375,
            17.8125,
            18.28125,
            18.75,
            19.21875,
            19.6875,
            20.15625,
            20.625,
            21.09375,
            21.5625,
            22.03125,
            22.5,
            22.96875,
            23.4375,
            23.90625,
            24.375,
            24.84375,
            25.3125,
            25.78125,
            26.25,
            26.71875,
            27.1875,
            27.65625,
            28.125,
            28.59375,
            29.0625,
            29.53125
        ],
        lindData2:[
            0.0004226875352970616,
            0.00034641497048504277,
            0.00021719346466619882,
            7.183311112335389e-05,
            5.0820062402756605e-05,
            0.00012232429849978743,
            0.00013276146876117778,
            9.177665019377557e-05,
            2.2637474020203996e-05,
            4.7829446528702135e-05,
            9.899827176784726e-05,
            0.00012181315213410926,
            0.00011810739674622539,
            9.563881743135383e-05,
            6.272837970389133e-05,
            2.5507192760620967e-05,
            1.2078030126261297e-05,
            4.7234310433186266e-05,
            7.751930632737825e-05,
            0.0001001877511490612,
            0.00011152247948986727,
            0.00010696715012192826,
            8.279427388968585e-05,
            3.8435695313143725e-05,
            2.225973478564569e-05,
            9.152614368845846e-05,
            0.00015923610395418564,
            0.00021457647328970708,
            0.0002476295170485976,
            0.0002512915788299708,
            0.00022366016097530306,
            0.00016998938784773543,
            0.00010281381716925608,
            3.947836384154968e-05,
            2.5762341375745734e-06,
            1.15026959868203e-05,
            1.4155067444843183e-05,
            6.359115462606368e-05,
            0.00011631662826205869,
            0.00014915861660247387,
            0.00014526051302832244,
            0.00010101660590056127,
            2.7656268452247446e-05,
            5.296390919040661e-05,
            0.00011606346998593864,
            0.00014198788729480327,
            0.00012241468246410037,
            6.375627400512229e-05,
            1.2932759324346677e-05,
            7.651111608675265e-05,
            9.512480151130376e-05,
            4.859869239037806e-05,
            6.071323662615313e-05,
            0.0002044264186094047,
            0.0003355825553157388,
            0.0004053509613211048,
            0.0003819975623651217,
            0.0002635537213300232,
            7.877864009442348e-05,
            0.00012325465074436437,
            0.0002898190827913538,
            0.0003805324637227159,
            0.00037710551204428455,
            0.0002847294912364795,
            0.0001269636455156764,
            6.176661960122232e-05,
            0.00024278466877758476,
            0.0003785166022987063,
            0.0004382467427812564,
            0.00040513982073342447,
            0.00028262885274221716,
            9.622845911083644e-05,
            0.00011207205532315356,
            0.0002956308158648113,
            0.0004162666130156367,
            0.00045346158995318575,
            0.00040718371060277647,
            0.0002947841864053835,
            0.00014397221303941166,
            1.544703953060278e-05,
            0.00015823321356567277,
            0.00026682004932476744,
            0.0003307471491931224,
            0.0003442199429564141,
            0.0003045833946382359,
            0.00021344963325242716,
            7.951109634518616e-05,
            7.991229747617012e-05,
            0.00024071620692467377,
            0.00037655117799895166,
            0.00046368674095642604,
            0.00048480130723049797,
            0.0004318306013528783,
            0.0003080129707551116,
            0.00012865962395469666,
            7.973232110369821e-05,
            0.00028231164195169356,
            0.0004413639565390426,
            0.0005246820785398398
        ],
        // 4.手臂弯曲
        vals41:"-",
        vals42:"-",
        nowDate:"",
        num: 3,
        //        time:"2022-04-22 10:56:08",
        startText:"开始检测",
        return_result: {
        },

        visible: false,  // 控制刷新的组件的显示

        //      时间参数
        last_update:'',
        nowtime:'',
        year:'',
        month:'',
        date:'',
        hour:'',
        minute:'',
        secondss:''
    },

    //获取当前时间方法
    get_time(){
        //定义Date类的对象now
        var now = new Date();
        //        获取当前年
        this.year = now.getFullYear().toString()
        //        获取当前月，需要加1，与实际月份相差1
        this.month = (now.getMonth()+1).toString()
        //        获取当前日期
        this.date = now.getDate().toString()
        //        获取当前小时
        this.hour = now.getHours().toString()
        //        获取当前分钟
        this.minute = now.getMinutes().toString()
        //        获取当前秒
        this.secondss = now.getSeconds().toString()
        //        数字位数小于2时加上0
        if(now.getMonth()+1<10){
            this.month = ("0"+ (now.getMonth()+1)).toString()
        }
        if(now.getDate()<10){
            this.date = "0"+ now.getDate().toString()
        }
        if(now.getHours()<10){
            this.hour = "0"+ now.getHours().toString()
        }
        if(now.getMinutes()<10){
            this.minute = "0"+ now.getMinutes().toString()
        }
        if(now.getSeconds()<10){
            this.secondss = "0"+ now.getSeconds().toString()
        }
        //        制定时间戳
        this.nowtime = this.year.toString() + this.month.toString() + this.date.toString() + this.hour.toString()+ this.minute.toString()+this.secondss.toString()
        //        格式化当前时间
        this.last_update = this.year + "年" + this.month + "月" + this.date + "日" + this.hour + ":" +this.minute + ":" + this.secondss
        //        打印时间戳和格式化时间
        console.info(this.nowtime)
        console.info(this.last_update)
        console.info("年："+this.year+"月："+this.month+"日："+this.date+"时："+this.hour+"分:"+this.minute+"秒:"+this.secondss)
    },

    showhintDialog(e) {
        this.$element('hintDialog').show()
    },

    sethintDialog(e) {
        this.$element('hintDialog').close()
    },

    tabChange(e){
        console.info("Tab index: " + e.index)
    },

    // 开始检测
    start_detection(types) {
        this.get_time();
        var type = types;
        var status = 'ON';
        let that = this;
        that.showhintDialog()  // 弹出准备对话框
        that.audioPlayerDemo()  // 音频播放
        // 等待检测，3S准备时间
        let prepareIntervalID = setInterval(function() {

            that.num--;  // 3S准备时间倒计时
            if(that.num==0){  // 3S倒计时结束
                that.sethintDialog()  // 隐藏准备对话框
                clearInterval(prepareIntervalID)  // 取消由 setInterval() 函数设定的定时执行操作

                prompt.showToast({
                    message: "开始检测",
                    duration: 2000,
                });
                // 命令下发，开始检测
                that.get_cd(type, status)
                return;
            }
        }, 1000)
    },



    // 重置用的tar会被重置成1，倒计时记录会归0
    remake(){
//        stateFlag=1;
        this.startText="开始检测"
        this.counter = 10;
    },

    // 音频播放
    async audioPlayerDemo() {
        let audioPlayer = media.createAudioPlayer();     //创建一个音频播放实例
        this.setCallBack(audioPlayer);                   //设置事件回调
        //        let fdPath = 'fd://'
        // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令，将其推送到设备上
        //        let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
        //        倒计时音频
        let fdPath = 'http://120.46.171.116/countdown.mp3'
        audioPlayer.src = fdPath; //设置src属性，并触发'dataLoad'事件回调
    },

    // 设置播放器回调函数
    setCallBack(audioPlayer) {
        audioPlayer.on('dataLoad', () => {              //设置'dataLoad'事件回调，src属性设置成功后，触发此回调
            console.info('audio set source success');
            audioPlayer.play();                           //调用play方法开始播放，触发'play'事件回调
        });
        audioPlayer.on('play', () => {                  //设置'play'事件回调
            console.info('audio play success');
        });
        audioPlayer.on('finish', () => {                //设置'finish'事件回调，播放完成触发
            console.info('audio play finish');
            audioPlayer.release();                        //audioPlayer资源被销毁
            audioPlayer = undefined;
        });
        audioPlayer.on('error', (error) => {             //设置'error'事件回调
            console.info(`audio error called, errName is ${error.name}`);
            console.info(`audio error called, errCode is ${error.code}`);
            console.info(`audio error called, errMessage is ${error.message}`);
        });
    },

    // 发送命令下发请求
    get_cd: function(types, status){

        let httpRequest = http.createHttp();
        // 创建一个http，里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header 事件。
        let url = "http://120.46.171.116:8082/get_command?types="+types+"&status="+status+'&account=15565988801'+'&time='+this.nowtime;
        let that = this;

        httpRequest.request(url, {
            // 注意请求方法：http.POST
            method: http.POST,
        }, (err, data)=> {  // 判断是否请求成功
            if (!err) {  // 请求成功
                console.log("命令下发成功")
                prompt.showToast({
                    message: "命令下发成功",
                    duration: 2000,
                });

                clearInterval(detectIntervalID);
                // 检测过程
                detectIntervalID = setInterval(function(){
                    that.run(types)
                }, 1000);
                that.startText="检测中..."


            } else {  // 请求失败
                prompt.showToast({
                    message: "命令下发失败",
                    duration: 3000,
                });

            }
        })

    },

    // 检测过程倒计时
    run(types){
        this.counter--;
        // tar等于2并且检测倒计时不等于-1：检测过程未结束，使progress圆环组件渲染到指定的百分比
        if (this.counter!=-1) {
            this.percentage = this.counter*20;  // 控制圆环组件百分比
            // 如果到0秒，检测倒计时结束
            if(this.counter==0){
                this.num = 3  // 重新赋值预备3S
                // 按钮变成重新检测
                this.startText = "重新测试"
            }
        } else {  // 检测过程结束
            clearInterval(detectIntervalID);
            detectIntervalID = null;
            this.counter = 5;  // 倒计时初始化为5秒
            this.percentage = 100;  // 圆环组件初始化为100
            let that = this;
            prompt.showToast({
                message: "检测成功",
                duration: 3000,
            })
            that.visible = true  // 开始刷新，显示刷新组件
            this.counter = 5
            // 延迟5000毫秒执行查询
            setTimeout(()=>{
                that.getData(types)  // 获取检测数据
                that.visible = false  // 结束刷新，显示刷新组件
            }, 5000)
        }
    },

    // 获取数据请求
    getData(types){
        if(types=="Kneading") {
            // 创建一个http请求
            let httpRequest = http.createHttp();
            let url = "http://120.46.171.116:8082/get_specified_kneading_data";
            httpRequest.request(url, {
                // 注意请求方法：http.POST
                method: http.POST,
                extraData: {
                    account:"15565988801",
                    time:this.nowtime
                },
            }, (err, data)=> {  // 判断是否请求成功
                if (!err) {  // 请求成功
                    this.return_result = JSON.parse(data.result);  //JSON.parse(字符串)：将字符串转换成json数据格式
                    this.vals11 = this.last_update;  //使用json赋值变量
                    this.vals12 = this.return_result.results[0].data.Kneading;
                    this.vals13 = this.return_result.results[0].data.kneadlevel;
                    console.info("捏合获取数据成功："+data.result)
                } else {  // 请求失败
                    var winfo = JSON.parse(data.result);
                    console.info("获取数据失败："+winfo)
                    prompt.showToast({
                        message: winfo,
                        duration: 3000,
                    });
                }
            })
        } else if(types=="Bend"){
            // 创建一个http请求
            let httpRequest = http.createHttp();
            let url = "http://120.46.171.116:8082/get_specified_bend_data";
            httpRequest.request(url, {
                method: http.POST,
                extraData: {
                    account:"15565988801",
                    time:this.nowtime
                },
            }, (err, data)=> {  // 判断是否请求成功
                if (!err) {  // 请求成功
                    this.return_result = JSON.parse(data.result);  //JSON.parse(字符串)：将字符串转换成json数据格式
                    this.vals21 = this.last_update;  //使用json赋值变量
                    this.vals22 = this.return_result.angle.bend_index_finger;
                    this.vals23 = this.return_result.angle.bend_middle_finger;
                    this.vals24 = this.return_result.angle.bend_ring_finger;
                    this.vals25 = this.return_result.angle.aver_bend_anger;
                    this.vals26 = this.return_result.stretchlevel;
                    console.info("弯曲角度获取数据成功："+data.result)
                } else {  // 请求失败
                    var winfo = JSON.parse(data.result);
                    console.info("获取数据失败："+winfo)
                    prompt.showToast({
                        message: winfo,
                        duration: 3000,
                    });
                }
            })

        } else if(types=="Tremor"){
            // 创建一个http请求
            let httpRequest = http.createHttp();
            let url = "http://120.46.171.116:8082/get_tremble_info";
            httpRequest.request(url, {
                method: http.POST,
                extraData: {
                    account:"15565988801",
                    time:this.nowtime
                },
            }, (err, data)=> {  // 判断是否请求成功
                if (!err) {  // 请求成功
                    this.return_result = JSON.parse(data.result);  //JSON.parse(字符串)：将字符串转换成json数据格式
                    this.vals31 = this.last_update;  //使用json赋值变量
                    this.vals32 = this.return_result.results.freq.frequency;
                    this.vals33 = this.return_result.results.jitter.mean_jitter;
                    this.vals34 = this.return_result.label;
                    this.lindData1 = this.return_result.results.freq.smoothed_spectrum;
                    this.lindData1 = this.return_result.results.jitter.jitter;
                    console.info("获取数据成功："+data.result)
                } else {  // 请求失败
                    var winfo = JSON.parse(data.result);
                    console.info("获取数据失败："+winfo)
                    prompt.showToast({
                        message: winfo,
                        duration: 3000,
                    });
                }
            })

        } else if(types=="Muscle"){
            // 创建一个http请求
            let httpRequest = http.createHttp();
            // 创建一个http，里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header 事件。
            let url = "http://120.46.171.116:8082/get_specified_muscle_data";
            httpRequest.request(url, {
                // 注意请求方法：http.POST
                method: http.POST,
                extraData: {
                    account:"15565988801",
                    time:this.nowtime
                },
            }, (err, data)=> {  // 判断是否请求成功
                if (!err) {  // 请求成功
                    this.return_result = JSON.parse(data.result);  //JSON.parse(字符串)：将字符串转换成json数据格式
                    this.vals41 = this.nowtime;  //使用json赋值变量
                    this.vals42 = this.return_result.results[0].Muscle.muscle;
                    console.info("获取数据失败："+data.result)
                } else {  // 请求失败
                    var winfo = JSON.parse(data.result);
                    console.info("获取数据失败："+winfo)
                    prompt.showToast({
                        message: winfo,
                        duration: 3000,
                    });
                }
            })
        }
    },

    //存储数据
    save_data(){
        let path;
        let context = featureAbility.getContext();
        context.getFilesDir().then((filePath) => {
            path = filePath;
            console.info("======================>getFilesDirPromise====================>");
            storage = data_storage.getStorageSync(path + '/mystore');
            // storage.putSync('vals13', this.vals13);
            // storage.putSync('vals12', this.vals13);
            // storage.putSync('vals26', this.vals26);
            // storage.putSync('vals26', this.vals25);
            // storage.putSync('vals34', this.vals34);
            // storage.putSync('vals34', this.vals32);
            // storage.putSync('vals34', this.vals33);
            // storage.putSync('lindData1', this.lindData1);
            // storage.putSync('lindData2', this.lindData2);
            storage.putSync('winfo', "传输成功");
            storage.flushSync();
        });
        router.push({
            uri:"pages/result/result",
            // params:{
            //     "vals13":this.vals13,
            //     "vals26":this.vals26,
            //     "vals34":this.vals34,
            //     "vals12":this.vals12,
            //     "vals25":this.vals25,
            //     "vals32":this.vals32,
            //     "vals33":this.vals33,
            //     "lindData1":this.lindData1,
            //     "lindData2":this.lindData2,
            //     "winfo":"传输成功！--------------"
            // }
        })
    }

}


